import * as THREE from "three";
import axios from 'axios';
import sceneMrg from "@/js/sceneMrg";
import startDrawCanvas from "./startDrawCanvas";
import imageLoad from './imageLoad';
import canvasEvent from "@/js/canvasEvent";

class Box {
    constructor(param) {
        this.param = param;
        this.node = this.param.data;
        this.canvas = '';
        this.img_height = 100;
        this.img_width = 100;

        this.init();
    }

    getDepth (data) {
        let name = data.type_name
        if(name.indexOf('服务器') > -1 || name.indexOf('存储设备') > -1||name.indexOf('安全设备') > -1) {
            return 0.7
        }else if(name.indexOf('配线架') > -1){
            return 0.005
        }else if(name.indexOf('网络设备') > -1 || name.indexOf('传输设备') > -1){
            if(data.height == 1) {
                return 0.3
            }
            if(data.height == 2) {
                return 0.4
            }
            return 0.5
        }

        return 1.15
    }

    async init() {
        let dh = this.param.deviceSlotHeight * this.param.data.height;
        let winpx = this.metersToPixels(dh);
        let winwidthpx = this.metersToPixels(0.5);
        console.log("高度为:", winpx);
        console.log("宽度:", winwidthpx);

        console.log("drawbg:", this.param)

        let depth = this.getDepth(this.param.data)

        const boxGeometry = new THREE.BoxGeometry(depth, dh, 0.5);
        const boxMaterial = await this.getMaterial({
            height: winpx,
            width: winwidthpx
        });

        this.box = new THREE.Mesh(boxGeometry, boxMaterial);
        this.box['modeldata'] = this.node;
        this.param.parent.add(this.box);
        this.box.position.x = (1.15 - depth)/2
        console.log("image 参数:", this.img_width, this.img_height);

        //this.box.position.x = (this.param.parent.geometry.parameters.width - depth) / 2; // 假设 parent 有一个几何体参数
        //this.box.position.y = (this.param.parent.geometry.parameters.height - dh) / 2; // 如果需要在 Y 轴上居中
        //this.box.position.z = 0; // 如果需要在 Z 轴上调整，也可以设置

        new startDrawCanvas({
            canvas: this.canvas,
            node: this.node,
            img_width: this.img_width,
            img_height: this.img_height,
            eq_width: winpx,
            eq_height: winwidthpx,
            texture: this.texture,
            ratio: winwidthpx / this.img_width
        });

        // 为 Canvas 添加点击事件
        // this.addCanvasClickListener(this.canvas, this.box);

        console.log("------dh-------:", dh);
    }

    metersToPixels(meters) {
        let camera = sceneMrg.camera;
        let renderer = sceneMrg.renderer;
        const fov = camera.fov * (Math.PI / 180); // 将 fov 转换为弧度
        const height = 2 * Math.tan(fov / 2) * camera.position.z; // 计算视锥体高度
        const pixelHeight = renderer.domElement.height; // 获取画布高度

        // 检查像素高度是否为零
        if (pixelHeight === 0) {
            console.error("Renderer height is zero.");
            return 0;
        }

        const pixelRatio = pixelHeight / height; // 计算像素与米的比例
        return meters * pixelRatio; // 返回转换后的像素
    }

    async drawLabel(param, url) {
        var canvas = document.createElement('canvas');
        let width = param.width;
        let height = param.height;

        canvas.width = width;
        canvas.height = height;
        canvas.style.width = width + 'px';
        canvas.style.height = height + 'px';
        var ctx = canvas.getContext('2d');
        ctx.fillRect(0, 0, width, height);

        await this.loadImage(ctx, param, url);

        // 在 (10, 10) 位置绘制一个红点
        ctx.fillStyle = 'red'; // 设置绘图颜色为红色
        ctx.fillRect(10, 10, 10, 10); // 绘制一个 1x1 像素的红点

        return canvas;
    }

    async loadImage(ctx, param, vurl) {
        let newUrl = vurl;
        let url = `api/${newUrl}`; // 替换为你的图片路径
        if (process.env.NODE_ENV === 'development') {
            console.log('现在是开发模式');
            newUrl = newUrl.replace('/v1', '');
            url = `api/${newUrl}`;
        } else {
            console.log('现在不是开发模式');
            url = newUrl;
        }
        let imageData = await imageLoad(url);
        this.img_width = imageData.width;
        this.img_height = imageData.height;
        ctx.drawImage(imageData.img, 0, 0, param.width, param.height);
    }

    async createView(param) {
        this.canvas = await this.drawLabel(param, this.node.back_view);
        const texture = new THREE.CanvasTexture(this.canvas);
        texture.needsUpdate = true; // 通知 Three.js 更新纹理
        this.texture = texture;
    }

    async createBackView(param) {
        this.backCanvas = await this.drawLabel(param, this.node.back_view);
        const texture = new THREE.CanvasTexture(this.backCanvas);
        texture.needsUpdate = true; // 通知 Three.js 更新纹理
        this.backtexture = texture;
        return texture;
    }

    async getMaterial(param) {
        let self = this;
        let backtexture = await this.createBackView(param);
        this.canvas = await this.drawLabel(param, this.node.view);
        new canvasEvent({
            canvas: this.canvas
        });
        const texture = new THREE.CanvasTexture(this.canvas);
        texture.needsUpdate = true; // 通知 Three.js 更新纹理
        this.texture = texture;

        let boxbg = 'boxbg.jpg'

        if(this.param.data.type_name == '服务器' || this.param.data.type_name == '存储设备'){
            boxbg = 'boxblock.png'
        }

        const textureLoader = new THREE.TextureLoader();
        return [
            new THREE.MeshBasicMaterial({
                map: texture,
                transparent: false,
                opacity: 1
            }),
            new THREE.MeshBasicMaterial({
                map: backtexture,
                transparent: true,
                opacity: 1
            }),
            new THREE.MeshBasicMaterial({
                color: '#C0C0C0',
                map: textureLoader.load(boxbg),
                transparent: true,
                opacity: 1
            }),
            new THREE.MeshBasicMaterial({
                color: '#C0C0C0',
                map: textureLoader.load(boxbg),
                transparent: true,
                opacity: 1
            }),
            new THREE.MeshBasicMaterial({
                color: '#C0C0C0',
                map: textureLoader.load(boxbg),
                transparent: true,
                opacity: 1
            }),
            new THREE.MeshBasicMaterial({
                color: '#C0C0C0',
                map: textureLoader.load(boxbg),
                transparent: true,
                opacity: 1
            })
        ];
    }

    addCanvasClickListener(canvas, mesh) {
        let camera = sceneMrg.camera;
        const raycaster = new THREE.Raycaster();
        const mouse = new THREE.Vector2();
        const renderer = sceneMrg.renderer;

        renderer.domElement.addEventListener('click', (event) => {
            // 转换鼠标位置为标准化坐标
            mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
            mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
            raycaster.setFromCamera(mouse, camera);

            // 检测交互
            const intersects = raycaster.intersectObject(mesh, true);
            if (intersects.length > 0) {
                const intersect = intersects[0];
                const uv = intersect.uv;

                // 转换 UV 坐标为 Canvas 像素坐标
                uv.multiplyScalar(canvas.width);
                const x = Math.floor(uv.x);
                const y = Math.floor(canvas.height - uv.y);

                console.log(`Clicked on Canvas at (${x}, ${y})`);

                // 在此处处理 Canvas 上的点击事件
                const ctx = canvas.getContext('2d');
                const pixel = ctx.getImageData(x, y, 1, 1).data;
                console.log(`Pixel data at (${x}, ${y}):`, pixel);

                // 确保绘制绿色方块
                ctx.fillStyle = 'green';
                ctx.fillRect(x - 50, y - 50, 300, 300);

                // 更新材质
                const texture = new THREE.CanvasTexture(canvas);
                mesh.material[0].map = texture;  // 假设第一个材质使用了 Canvas 纹理
                texture.needsUpdate = true;

                console.log("材质更新成功");
            } else {
                console.log("未检测到交互");
            }
        });
    }
}

export default Box;
